package com.iqiyi.pps.epg.core.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iqiyi.kiwi.utils.Configuration;
import com.iqiyi.pps.epg.core.model.channel.ChannelConfig;
import com.iqiyi.pps.epg.core.model.program.ProgramData;
import com.iqiyi.pps.epg.core.service.program.ProgramService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Created by zhangjing on 2017/3/21.
 */
public class ApiDirectorUtil {
    private static final Logger logger = LoggerFactory.getLogger(ApiDirectorUtil.class);
    public static final String ERROR_CODE = "error_code";

    private static final boolean testMode = false;

    private ApiDirectorUtil() {
    }

    private static String addSourceUrl = Configuration.getString("director.server.addsource", "http://YW-A2980-D.iqiyi.pps/addsource");
    private static String removeSourceUrl = Configuration.getString("director.server.removesource", "http://YW-A2980-D.iqiyi.pps:8002/removesource");
    private static String switchSourceUrl = Configuration.getString("director.server.switchsource", "http://YW-A2980-D.iqiyi.pps:8002/switchsource");
    private static String updateSourceUrl = Configuration.getString("director.server.updatesource", "http://YW-A2980-D.iqiyi.pps:8002/updatesource");

    private static String stopProgramUrl = Configuration.getString("director.server.stopprogram");
    private static String releaseProgramUrl = Configuration.getString("director.server.releaseprogram");
    private static String startProgramUrl = Configuration.getString("director.server.startprogram");
    private static String updateProgramUrl = Configuration.getString("director.server.updateprogram");

    private static String registerOutputUrl = Configuration.getString("director.server.registerOutput");
    private static String publishStopUrl = Configuration.getString("director.server.publishStop");

    private static String addResourceUrl = Configuration.getString("director.server.addresource", "http://YW-A2980-D.iqiyi.pps/addresource");
    private static String removeResourceUrl = Configuration.getString("director.server.removeresource", "http://YW-A2980-D.iqiyi.pps:8002/removeresource");
    private static String updateResourceUrl = Configuration.getString("director.server.updateresource", "http://YW-A2980-D.iqiyi.pps:8002/updateresource");
    private static String startPreviewUrl = Configuration.getString("director.server.startpreview", "http://YW-A2980-D.iqiyi.pps:8002/startpreview");
    private static String startPreviewUrlUrl = Configuration.getString("director.server.startpreviewurl", "http://YW-A2980-D.iqiyi.pps:8002/startpreviewurl");
    private static String stopPreviewUrlUrl = Configuration.getString("director.server.stoppreviewurl", "http://YW-A2980-D.iqiyi.pps:8002/stoppreviewurl");
    private static String stopCommentaryUrl = Configuration.getString("director.server.stopcommentary", "http://YW-A2980-D.iqiyi.pps:8002/stopcommentary");

    public static boolean isProductionEnv() {
        return "production".equals(Configuration.getString("deploy.env"));
    }

    public static JSONObject addSource(String jsonParams, String pid) {
        if (testMode) {
            JSONObject temp = new JSONObject();
            temp.put("error_code", Constants.CODE_SUC);
            temp.put("result", "http://10.110.48.109:8001/querysource?ID=2055");
            return temp;
        }
        JSONObject jsonObject = ApiHttpRequestUtil.doPostRaw(addSourceUrl + "?PID=" + pid, jsonParams);
        return jsonObject;
    }

    public static boolean updateSource(String id, String pid, String playCounts) {
        if (testMode) {
            return true;
        }
        Map<String, String> map = new HashMap<>();
        map.put("ID", id);
        map.put("PID", pid);
        map.put("REPEAT", playCounts);
        JSONObject jsonObject = ApiHttpRequestUtil.getMethod(updateSourceUrl, map, null);
        if (jsonObject != null && Constants.CODE_SUC.equals(jsonObject.get(ERROR_CODE))) {
            return true;
        }
        return false;
    }

    public static boolean removeSource(String id, String pid) {
        if (testMode) {
            return true;
        }
        Map<String, String> map = new HashMap<>();
        map.put("ID", id);
        map.put("PID", pid);
        JSONObject jsonObject = ApiHttpRequestUtil.getMethod(removeSourceUrl, map, null);
        if (jsonObject != null && Constants.CODE_SUC.equals(jsonObject.get(ERROR_CODE))) {
            return true;
        }
        return false;
    }

    public static JSONObject switchSource(Map<String, String> params) {
        if (testMode) {
            JSONObject temp = new JSONObject();
            temp.put("error_code", Constants.CODE_SUC);
            temp.put("result", "demoUrl");
            return temp;
        }
        JSONObject jsonObject = ApiHttpRequestUtil.getMethod(switchSourceUrl, params, null);
        return jsonObject;
//        if (jsonObject != null && Constants.CODE_SUC.equals(jsonObject.get(ERROR_CODE))) {
//            return true;
//        }
//        return false;
    }

    public static String doRegisterOutputUrl(long qipuId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("user_id", "directorId" + qipuId);
        String useIp = null;
        if (isProductionEnv()) {
            List<ChannelConfig> list = WriteSystemLogUtil.getInstance().getChannelService().getConfig("director_ip");
            if (list.size() > 0) {
                useIp = list.get(0).getVal();
            }
            if (useIp == null || useIp.length() < 5) {
                useIp = RequestUtils.getLoadlIpByOS();
            }
        } else {
            useIp = RequestUtils.getLoadlIpByOS();
        }

        params.put("user_cip", useIp);
        //    params.put("user_net","");
        params.put("user_ip", useIp);
        params.put("user_type", 0);
        params.put("switch_type", 0);
        params.put("valid_for", 2592000);
        params.put("authenticate_valid", 2592000);
        params.put("disconnect_valid", 2592000);
        //    params.put("pushserver_eip","");
        params.put("seq_no", new Random().nextInt(100));
        params.put("app_type", "PPC");
        JSONObject jsonObject = ApiHttpRequestUtil.getMethod(registerOutputUrl, params, null);
        if (null != jsonObject) {
            writeProgramLogByQipuId(qipuId, Constants.LogType.DIRECTOR_REGISTER_OUTPUT_URL.getIndex(),
                    "addDirector |[doRegisterOutputUrl]url:" + registerOutputUrl +
                            " | param: " + JSON.toJSONString(params) +
                            " | result:　" + jsonObject.toJSONString());
            if (1 == jsonObject.getIntValue("ret_status")) {
                return jsonObject.getString("internal_push_url");
            } else {
                return null;
            }

        }else {
            writeProgramLogByQipuId(qipuId, Constants.LogType.DIRECTOR_REGISTER_OUTPUT_URL.getIndex(),
                    "addDirector |[doRegisterOutputUrl]url:" + registerOutputUrl +
                            " | param: " + JSON.toJSONString(params) +
                            " | result:　jsonObject == null | third-party api get response error ?");

        }
        return null;
    }
    private static void writeProgramLogByQipuId(long programQipuId, int type, String descr) {
        try {
            ProgramService service = WriteSystemLogUtil.getInstance().getProgramService();
            ProgramData programData = service.findProgramDataByQipuId(programQipuId);
            WriteSystemLogUtil.getInstance().writeProgramLog(programData.getId(), type, descr);
        } catch (Exception e) {
            logger.info("[writeProgramLogByQipuId] e = " + e);
        }
    }

    public static boolean unRegisterUrl(String streamName, String authCode) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("stream_name", streamName);
        params.put("auth_code", authCode);
        params.put("app_type", "PPC");
        JSONObject jsonObject = ApiHttpRequestUtil.getMethod(publishStopUrl, params, null);
        if (jsonObject != null && 1 == jsonObject.getIntValue("ret_status")) {
            return true;
        }
        return false;
    }

    public static JSONObject doStartDirector(String jsonString, String pid, String region) {
        if (testMode) {
            JSONObject temp = new JSONObject();
            temp.put("error_code", Constants.CODE_SUC);
            temp.put("result", "demoUrl");
            return temp;
        }
        JSONObject jsonObject = ApiHttpRequestUtil.doPostRaw(
                startProgramUrl + "?PID=" + pid + "&REGION=" + region, jsonString);
        return jsonObject;
    }

    public static boolean doUpdateDirector(String jsonString, String pid) {
        if (testMode) {
            return true;
        }
        JSONObject jsonObject = ApiHttpRequestUtil.doPostRaw(updateProgramUrl + "?PID=" + pid, jsonString);
        if (jsonObject != null && Constants.CODE_SUC.equals(jsonObject.get(ERROR_CODE))) {
            return true;
        }
        return false;
    }


    public static boolean doStopDirector(Map<String, ? extends Object> params) {
        if (testMode) {
            return true;
        }
        JSONObject jsonObject = ApiHttpRequestUtil.getMethod(stopProgramUrl, params, null);
        if (jsonObject != null && Constants.CODE_SUC.equals(jsonObject.get(ERROR_CODE))) {
            return true;
        }
        return false;
    }

    public static JSONObject doReleaseDirector(Map<String, ? extends Object> params) {
        if (testMode) {
            JSONObject temp = new JSONObject();
            temp.put("error_code", Constants.CODE_SUC);
            temp.put("result", "demoUrl");
            return temp;
        }

        JSONObject jsonObject = ApiHttpRequestUtil.getMethod(releaseProgramUrl, params, null, 60000);
        return jsonObject;
//        if (jsonObject != null && Constants.CODE_SUC.equals(jsonObject.get(ERROR_CODE))) {
//            return true;
//        }
//        return false;
    }

    public static JSONObject addResource(String pid, String jsonParams) {
        if (testMode) {
            JSONObject temp = new JSONObject();
            temp.put("error_code", Constants.CODE_SUC);
            temp.put("result", "demoUrl");
            return temp;
        }
        JSONObject jsonObject = ApiHttpRequestUtil.doPostRaw(addResourceUrl + "?PID=" + pid, jsonParams);
        return jsonObject;
    }

    public static JSONObject updateResource(String pid, String id, String jsonParams) {
        if (testMode) {
            JSONObject temp = new JSONObject();
            temp.put("error_code", Constants.CODE_SUC);
            temp.put("result", "demoUrl");
            return temp;
        }
        JSONObject jsonObject = ApiHttpRequestUtil.doPostRaw(
                updateResourceUrl + "?PID=" + pid + "&ID=" + id, jsonParams);
        return jsonObject;
    }

    public static JSONObject startPreview(String pid, String id, String jsonParams) {
        if (testMode) {
            JSONObject temp = new JSONObject();
            temp.put("error_code", Constants.CODE_SUC);
            temp.put("result", 1);
            return temp;
        }

        JSONObject jsonObject = ApiHttpRequestUtil.doPostRawNolog(
                startPreviewUrl + "?PID=" + pid + "&ID=" + id, jsonParams);
        return jsonObject;
    }

    public static boolean removeResource(String id, String pid) {
        if (testMode) {
            return true;
        }
        Map<String, String> map = new HashMap<>();
        map.put("ID", id);
        map.put("PID", pid);
        JSONObject jsonObject = ApiHttpRequestUtil.getMethod(removeResourceUrl, map, null);
        if (jsonObject != null && Constants.CODE_SUC.equals(jsonObject.get(ERROR_CODE))) {
            return true;
        }
        return false;
    }

    public static JSONObject startPreviewUrl(String pid, String signalUrl) {
        if (testMode) {
            JSONObject temp = new JSONObject();
            temp.put("error_code", Constants.CODE_SUC);
            temp.put("result", "rtmp://test");
            return temp;
        }
        Map<String, String> map = new HashMap<>();
        map.put("src", signalUrl);
        map.put("PID", pid);
        JSONObject jsonObject = ApiHttpRequestUtil.getMethod(startPreviewUrlUrl, map, null);
        return jsonObject;
    }

    public static JSONObject stopPreviewUrl(String pid, String previewUrl) {
        if (testMode) {
            JSONObject temp = new JSONObject();
            temp.put("error_code", Constants.CODE_SUC);
            temp.put("result", 1);
            return temp;
        }
        Map<String, String> map = new HashMap<>();
        map.put("src", previewUrl);
        map.put("PID", pid);
        JSONObject jsonObject = ApiHttpRequestUtil.getMethod(stopPreviewUrlUrl, map, null);
        return jsonObject;
    }

    public static JSONObject stopCommentary(String pid, String id) {
        if (testMode) {
            JSONObject temp = new JSONObject();
            temp.put("error_code", Constants.CODE_SUC);
            temp.put("result", 1);
            return temp;
        }

        Map<String, String> map = new HashMap<>();
        map.put("ID", id);
        map.put("PID", pid);
        JSONObject jsonObject = ApiHttpRequestUtil.getMethod(stopCommentaryUrl, map, null);
        return jsonObject;
    }
}
